#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import counters
import counter_conf
import permission

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None
        #get each counter value
        counterInfoList = []
        for counterType in counter_conf.counterTypes:
            counter = counters.AtomicCounter(counterType)
            counterValue = counter.getCounter()
            counterInfo = (counterType, counterValue)
            counterInfoList.append(counterInfo)
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'xnuid': xnuid,
            'nav_selected': 'counter',
            'counterInfoList': counterInfoList,
            'callbackUrl': callbackUrl
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/admin/counter.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None
            
        counterType = self.request.get('counter_type')
        counterInit = self.request.get('counter_init')
        if counterType and counterType not in counter_conf.counterTypes:
            counterType = counter_conf.counterTypes[0]
        try:
            initValue = int(counterInit)
        except ValueError:
            initValue = 0
        counter = None
        if counterType:
            counter = counters.AtomicCounter(counterType)
            counter.init(initValue)
            
        if counter:
            counterValue = counter.getCounter()
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'xnuid': xnuid,
            'callbackUrl': callbackUrl
        }
        self.redirect(callbackUrl)
        return None

application = webapp.WSGIApplication(
                                     [('/admin/counter', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
